function extractAppNames() {
    const result = [];

    document.querySelectorAll('tbody tr').forEach(tr => {
        const td = tr.querySelectorAll('td')[2];
        if (td) {
            const span = td.querySelector('span.el-link--inner');
            if (span) {
                const text = span.textContent.trim().replace(/_/g, '-');
                if (text) {
                    result.push(text);
                }
            }
        }
    });

    return result;
}

function generateKibanaUrl(result) {
    const paramList = result.join(',');
    const shouldList = result.map(name => `(match_phrase:(appName:${name}))`).join(',');
    const baseUrl = 'https://global-testing-kibana.hszq8.com/app/discover#/';
    const prodBaseUrl = 'https://hk-logcenter-kibana-prod.hszq8.com/app/discover#/';
    const uatIndexId = 'bdef1050-8160-11f0-b9d8-272267e3c385';
    const featureIndexId = '6f10c960-8160-11f0-b9d8-272267e3c385';
    const prodIndexId = 'd2a39330-e11d-11ed-a621-052deba84007';

    const uatUrl = `${baseUrl}?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(` +
        `columns:!(appName,msg,logger),` +
        `filters:!((` +
        `'$state':(store:appState),` +
        `meta:(alias:!n,disabled:!f,index:${uatIndexId},key:appName,negate:!f,params:!(${paramList}),type:phrases,value:'${paramList}'),` +
        `query:(bool:(minimum_should_match:1,should:!(${shouldList})))))` +
        `,index:${uatIndexId},interval:auto,query:(language:kuery,query:''),sort:!())`;
    const featureUrl = `${baseUrl}?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(` +
        `columns:!(appName,msg,logger),` +
        `filters:!((` +
        `'$state':(store:appState),` +
        `meta:(alias:!n,disabled:!f,index:${featureIndexId},key:appName,negate:!f,params:!(${paramList}),type:phrases,value:'${paramList}'),` +
        `query:(bool:(minimum_should_match:1,should:!(${shouldList})))))` +
        `,index:${featureIndexId},interval:auto,query:(language:kuery,query:''),sort:!())`;
    const prodUrl = `${prodBaseUrl}?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(` +
        `columns:!(appName,msg,logger),` +
        `filters:!((` +
        `'$state':(store:appState),` +
        `meta:(alias:!n,disabled:!f,index:${prodIndexId},key:appName,negate:!f,params:!(${paramList}),type:phrases,value:'${paramList}'),` +
        `query:(bool:(minimum_should_match:1,should:!(${shouldList})))))` +
        `,index:${prodIndexId},interval:auto,query:(language:kuery,query:''),sort:!())`;

    console.log('[flow_detail.js] Kibana uat URL:', uatUrl);
    console.log('[flow_detail.js] Kibana feature URL:', featureUrl);
    console.log('[flow_detail.js] Kibana prod URL:', uatUrl);
    waitForContainerAndInsert(featureUrl, uatUrl, prodUrl);

}

function waitForContainerAndInsert(featureUrl, uatUrl, prodUrl, maxRetries = 200, interval = 300) {
    let tryCount = 0;

    const tryInsert = () => {
        const container = document.querySelector('#pane-branch_app_list > div');
        const buttons = container?.querySelectorAll('button');
        const hasAddButton = Array.from(buttons || []).some(btn =>
            btn.textContent.includes('刷新')
        );

        if (container && hasAddButton) {
            console.log('[flow_detail.js] 插入按钮容器及内容已就绪');
            insertLogButton(featureUrl, uatUrl, prodUrl);
        } else if (tryCount < maxRetries) {
            tryCount++;
            setTimeout(tryInsert, interval);
        } else {
            console.warn('[flow_detail.js] 容器或按钮区域渲染超时，插入按钮失败');
        }
    };

    tryInsert();
}

function insertLogButton(featureUrl, uatUrl, prodUrl) {
    const container = document.querySelector('#pane-branch_app_list > div');
    if (!container) {
        console.warn('[flow_detail.js] 未找到按钮容器');
        return;
    }

    // 创建按钮
    const logButton = document.createElement('button');
    logButton.className = 'el-button el-button--success el-button--small is-round log-button-trigger';
    logButton.style.position = 'relative';
    logButton.style.marginLeft = '10px';
    logButton.innerHTML = `<i class="el-icon-view"></i><span>查看Kibana日志</span>`;

    // 创建浮窗
    const dropdown = document.createElement('div');
    dropdown.className = 'log-env-dropdown';
    dropdown.style.cssText = `
        display: none;
        position: absolute;
        top: 36px;
        left: 0;
        background: #fff;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
        z-index: 9999;
        padding: 5px 0;
        min-width: 100px;
    `;

    const envList = ['feature', 'uat', 'prod'];
    envList.forEach(env => {
        const item = document.createElement('div');
        item.textContent = env.toUpperCase();
        item.style.cssText = `
            padding: 6px 16px;
            cursor: pointer;
            color: #409EFF;
            font-size: 14px;
        `;
        item.addEventListener('click', e => {
            e.stopPropagation();
            if (env === 'uat') {
                window.open(uatUrl, '_blank');
            } else if (env === 'feature') {
                window.open(featureUrl, '_blank');
            } else if (env === 'prod') {
                window.open(prodUrl, '_blank');
            } else {
                console.log(`[flow_detail.js] 点击了 ${env}，暂未实现跳转`);
            }
            dropdown.style.display = 'none'; // 点击后隐藏浮窗
        });
        dropdown.appendChild(item);
    });

    logButton.appendChild(dropdown);

    // 鼠标移入显示，移出隐藏
    logButton.addEventListener('mouseenter', () => {
        dropdown.style.display = 'block';
    });
    logButton.addEventListener('mouseleave', () => {
        // 用定时器延迟隐藏，防止快速移入移出闪烁
        setTimeout(() => {
            if (!dropdown.matches(':hover') && !logButton.matches(':hover')) {
                dropdown.style.display = 'none';
            }
        }, 150);
    });
    dropdown.addEventListener('mouseleave', () => {
        setTimeout(() => {
            if (!dropdown.matches(':hover') && !logButton.matches(':hover')) {
                dropdown.style.display = 'none';
            }
        }, 150);
    });

    // 插入按钮
    const tableDiv = container.querySelector('div.el-table');
    if (tableDiv) {
        container.insertBefore(logButton, tableDiv);
        console.log('[flow_detail.js] 按钮插入到 el-table 之前');
    } else {
        container.appendChild(logButton);
        console.warn('[flow_detail.js] 未找到 el-table，按钮已插入到容器末尾');
    }
}


function waitForAppNames(maxRetries = 100, interval = 300) {
    let attempt = 0;

    const tryExtract = () => {
        const result = extractAppNames();
        if (result.length > 0) {
            console.log(`[flow_detail.js] 成功提取 appName，共 ${result.length} 个`);
            generateKibanaUrl(result);
        } else if (attempt < maxRetries) {
            attempt++;
            setTimeout(tryExtract, interval);
        } else {
            console.warn('[flow_detail.js] 超过最大轮询次数，未能提取到有效 appName');
        }
    };

    tryExtract();
}

// 启动轮询
waitForAppNames();
